package com.sx.medicinecard.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sx.medicinecard.service.HyService;
import com.sx.medicinecard.utils.HttpUtils;
import com.sx.medicinecard.utils.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.Map;


/**
 * 荷叶服务
 */

@Slf4j
@Service
public class HyServiceimpl implements HyService {

    @Value("${heye.channelCode}")
    private String heyeChannelCode;

    @Value("${heye.appId}")
    private String heyeAppId;

    @Value("${heye.secretKey}")
    private String heyeSecretKey;

    @Value("${heye.activationRights}")
    private String heyeActivationRightsUrl;


    /**
     * 刷单激活权益
     * @param phoneNo
     * @return
     */

    @Override
    public String activationRights(String phoneNo) {

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 获取一年后的时间
        LocalDateTime oneYearLater = now.plusYears(1);

        // 将一年后的时间转换为时间戳，并转换为秒为单位的10位时间戳
        long oneYearLaterTimeStamp = oneYearLater.toEpochSecond(ZoneOffset.UTC);


        JSONObject paramJson = new JSONObject();
        paramJson.put("userPhone",phoneNo);
        paramJson.put("channelCode",heyeChannelCode);
        paramJson.put("startTime",System.currentTimeMillis() / 1000);
        paramJson.put("endTime",oneYearLaterTimeStamp);

        JSONObject sendJson = new JSONObject();
        sendJson.put("appId", heyeAppId);
        sendJson.put("timestamp", System.currentTimeMillis() / 1000);
        sendJson.put("paramJson", JSON.toJSONString(paramJson));
        String signature = SignUtil.generateSign(sendJson, heyeSecretKey);
        sendJson.put("sign", signature);
        log.info("请求荷叶刷单权益卡激活");
        String string = HttpUtils.doPost(sendJson, heyeActivationRightsUrl);
        if("success".equals(JSONObject.parseObject(string).getString("msg"))){
            String receiveId = JSONObject.parseObject(string).getJSONObject("data").getString("receiveId");
            log.info("荷叶返回刷单权益卡id：{}",receiveId);
            return receiveId;
        }
        return null;
    }
}
